﻿using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;

namespace PageOffice6_Net_Core.Controllers.SaveAsPDF
{
    public class SaveAsPDFController : Controller
    {
        private readonly IWebHostEnvironment _webHostEnvironment;
        protected string pdfName = "";
        public SaveAsPDFController(IWebHostEnvironment webHostEnvironment)
        {
            _webHostEnvironment = webHostEnvironment;
        }


        public IActionResult OpenPDF()
        {
            PageOfficeNetCore.PDFCtrl pdfCtrl = new PageOfficeNetCore.PDFCtrl(Request);
            string fileName = Request.Query["fileName"];
            pdfCtrl.WebOpen("doc/" + fileName);

            ViewBag.pdfCtrl = pdfCtrl.GetHtml();
            return View();
        }

        public IActionResult WordToPDF()
        {
            PageOfficeNetCore.PageOfficeCtrl poCtrl = new PageOfficeNetCore.PageOfficeCtrl(Request);

            string fileName = "template.doc";
            //定义将要转换的PDF文件的名称
            pdfName = fileName.Substring(0, fileName.Length - 4) + ".pdf";

            //打开Word文档
            poCtrl.WebOpen("doc/" + fileName, PageOfficeNetCore.OpenModeType.docNormalEdit, "tom");
            ViewBag.poCtrl = poCtrl.GetHtml();
            ViewBag.pdfName = pdfName;
            return View();
        }


        public async Task<ActionResult> SaveDoc()
        {
            PageOfficeNetCore.FileSaver fs = new PageOfficeNetCore.FileSaver(Request, Response);
            await fs.LoadAsync();
            string webRootPath = _webHostEnvironment.WebRootPath;
            fs.SaveToFile(webRootPath + "/SaveAsPDF/doc/" + fs.FileName);
            return fs.Close();
            
        }
    }
}